#include <xsocketdefine.h>
#include <xsocketapi.h>
#include "xudpclient.h"
namespace zdh
{
    

    XUDPClient::XUDPClient()
        :m_Dest(NULL),m_IP("127.0.0.1"),m_Port(1234),m_Active(false)
    {
        m_Dest = (void *)new sockaddr();
    }

    XUDPClient::~XUDPClient()
    {
        Close();
        if( m_Dest != NULL )
        {
            delete (sockaddr *)m_Dest;
            m_Dest = NULL;
        }
    }

    void XUDPClient::Open()
    {
        if( !m_Active )
        {
            m_Socket.Open(XST_SOCK_DGRAM);
            if( !m_Socket.isInvalid() ) m_Active = true;
        }
    }

    void XUDPClient::Close()
    {
        if( m_Active ) 
        {
            m_Socket.Close();
            m_Active = false;
        }
    }

    void XUDPClient::setDest( const XString & aIP,XWord aPort )
    {
        if( m_IP != aIP || m_Port != aPort )
        {
            sockaddr_in * aRemote = (sockaddr_in *)m_Dest;
            aRemote->sin_family = AF_INET;
            aRemote->sin_addr.s_addr = XSocketAPI::INet_addr(aIP.c_str());
            aRemote->sin_port = XSocketAPI::HostToNetworkShort(aPort);
            m_IP = aIP;
            m_Port = aPort;
            for(int i=0;i<8;i++) aRemote->sin_zero[i] = 0;
        }
    }
    void XUDPClient::setDest( const char * aIP,XWord aPort )
    {
        if( m_IP != aIP || m_Port != aPort )
        {
            sockaddr_in * aRemote = (sockaddr_in *)m_Dest;
            aRemote->sin_family = AF_INET;
            aRemote->sin_addr.s_addr = XSocketAPI::INet_addr(aIP);
            aRemote->sin_port = XSocketAPI::HostToNetworkShort(aPort);
            m_IP = aIP;
            m_Port = aPort;
            for(int i=0;i<8;i++) aRemote->sin_zero[i] = 0;
        }
    }
    int XUDPClient::SendData( const void * aData,int aDataSize )
    {
        int iRet;
        if( m_Active )
        {
            iRet = (int)XSocketAPI::SendTo(_HANDLE_(m_Socket),(const char *)aData,aDataSize,0,(const sockaddr *)m_Dest,sizeof(sockaddr_in));
        }
        else iRet = -1;
        return iRet;
    }
    int XUDPClient::SendData(const void * aData,int aDataSize,void * to)
    {
        int iRet;
        if( m_Active )
        {
            iRet = (int)XSocketAPI::SendTo(_HANDLE_(m_Socket),(const char *)aData,aDataSize,0,(const sockaddr *)to,sizeof(sockaddr_in));
        }
        else iRet = -1;
        return iRet;

    }
}
